
import csv
from datetime import time
import json
import json
import time
import matplotlib.colors as mcolors
import math
import matplotlib.pyplot as plt
import random
import numpy as np
import pandas as pd
import sesson3.subject1.ss3_1 as s31
import sesson3.subject1.base_fun as bf
import sesson3.subject1.networkx_graph31 as ng31
import sesson1.globalvar as Globalvar
from .import session3_1_main as s31main
import copy

# from .import ss3_1 as s31
# from .import base_fun as bf
# from .import networkx_graph31 as ng31
# if True:
#     from .import ss3_1 as s31
#     from .import base_fun as bf
#     from .import networkx_graph31 as ng31
# else:
# import ss3_1 as s31
# import base_fun as bf
# import networkx_graph31 as ng31
import networkx as nx
import configparser
import sesson1.globalvar as Globalvar
import sesson1.udp as udp
import sesson1.run as sesson1
colors = list(dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS).keys())
update_new_break = False
e_round = 0

speed_dict = [0, 0.56, 1.94, 1.38, 0.83, 0.2]


def gen_place(place_type, operate_id, place__index):
    SCHOOL = 1
    plen = len(place_type)
    # print(place_type,place__index)
    people_place_id = []
    if plen == 3:  # 3个地点
        if SCHOOL in place_type:  # 有学校
            people_place_id += [SCHOOL for i in range(92)]  # 学校90
            for val in place_type:
                if val == SCHOOL:  # 学校
                    continue
                elif val == 2:  # 公园
                    people_place_id += [val for i in range(206)]
                elif val == 3:  # 体育场
                    people_place_id += [val for i in range(206)]
                elif val == 4:  # 医院
                    people_place_id += [val for i in range(206)]
                elif val == 5:  # 空地
                    people_place_id += [val for i in range(206)]
                print(len(people_place_id), val)
        else:  # 没有学校，3个场地按比例分人
            for val in place_type:
                if val == SCHOOL:  # 学校
                    people_place_id += [val for i in range(166)]
                if val == 2:  # 公园
                    people_place_id += [val for i in range(166)]
                elif val == 3:  # 体育场
                    people_place_id += [val for i in range(166)]
                elif val == 4:  # 医院
                    people_place_id += [val for i in range(166)]
                elif val == 5:  # 空地
                    people_place_id += [val for i in range(166)]
            # people_place_id = [random.choice(place_type) for i in range(500)]
    elif plen == 5:
        if SCHOOL in place_type:  # 有学校
            people_place_id += [SCHOOL for i in range(68)]  # 学校90
            for val in place_type:
                if val == SCHOOL:
                    continue
                if val == 2:  # 公园
                    people_place_id += [val for i in range(144)]
                if val == 3:  # 体育场
                    people_place_id += [val for i in range(144)]
                if val == 4:  # 医院
                    people_place_id += [val for i in range(144)]
                if val == 5:
                    continue
                # people_place_id += [val for i in range(144)]
                # print(len(people_place_id), val)
        else:  # 没有学校，5个场地按比例分人
            for val in place_type:
                if val == SCHOOL:  # 学校
                    people_place_id += [val for i in range(100)]
                if val == 2:  # 公园
                    people_place_id += [val for i in range(100)]
                elif val == 3:  # 体育场
                    people_place_id += [val for i in range(200)]
                elif val == 4:  # 医院
                    people_place_id += [val for i in range(100)]
                elif val == 5:  # 空地
                    people_place_id += [val for i in range(0)]
            # people_place_id = [random.choice(place_type) for i in range(500)]
    elif plen == 4:
        if SCHOOL in place_type:  # 有学校
            people_place_id += [SCHOOL for i in range(80)]  # 学校90
            for val in place_type:
                if val == SCHOOL:
                    continue
                elif val == 2:  # 公园
                    people_place_id += [val for i in range(140)]
                elif val == 3:  # 体育场
                    people_place_id += [val for i in range(140)]
                elif val == 4:  # 医院
                    people_place_id += [val for i in range(140)]
                elif val == 5:  # 空地
                    people_place_id += [val for i in range(140)]
                # if val == 5:
                #     continue
                # people_place_id += [val for i in range(140)]
                print(len(people_place_id), val)
        else:  # 没有学校，5个场地按比例分人
            for val in place_type:
                if val == SCHOOL:  # 学校
                    people_place_id += [val for i in range(125)]
                if val == 2:  # 公园
                    people_place_id += [val for i in range(125)]
                elif val == 3:  # 体育场
                    people_place_id += [val for i in range(125)]
                elif val == 4:  # 医院
                    people_place_id += [val for i in range(125)]
                elif val == 5:  # 空地
                    people_place_id += [val for i in range(125)]
            # people_place_id = [random.choice(place_type) for i in range(500)]
    else:
        people_place_id = [random.choice(place_type) for i in range(500)]

    # print(people_place_id)
    return people_place_id[:500]


def s31_2json_new(data_set, paths, place_points, operate_id, place_id, place_type, PEOPLE, place_map_id):
    # spath = "ai_path_"+str(operate_id)+".json"
    RoadLine = dict()
    fline = dict()
    for i in range(len(place_points)):
        temp_dict = dict()
        temp_dict["place_id"] = place_id[i]
        temp_dict["people"] = list()
        # fline.setdefault("places", []).append(
        #     temp_dict.copy())  # 根据文件大小确定答案的places个数

        RoadLine.setdefault("firstPlaces", []).append(copy.deepcopy(temp_dict))
        RoadLine.setdefault("secondPlaces", []).append(
            copy.deepcopy(temp_dict))
    RoadLine.setdefault("operate_id", operate_id)
    # with open(spath, 'w', encoding='utf-8') as f:
    #     f.write(json.dumps(RoadLine, ensure_ascii=False))
    print("place_id ", place_id, "place_type ", place_type)
    # px = {"longitude": 105.53628319629698, "latitude": 38.832731900565818}
    # RoadLine["operate_id"] = 3
    peodic = {
        "people_id": 494,
        "people_type": 5,
        "pass_points":  []}
    # print(data_set, len(peole_path))
    asum = []
    rate = get_rate(operate_id)
    print("rate ", rate)
    for h in range(500):
        if random.uniform(0, 1) > rate:
            continue

        place_target_type = PEOPLE.end1[h]

    #     (p_id8, p_point, jsond3) = paths[place_target_type]
    #     # paths.ge
    #     # print(len(jsond3[0]))
    #     # print(paths[people_type] )
        cid = PEOPLE.path1.cid[h]
        peodic["people_id"] = PEOPLE.id[h]
        peodic["people_type"] = PEOPLE.type[h]
        peodic["pass_points"] = PEOPLE.path1.pjson[h][0:cid]
    #     # print(rd)
    #     peodic["pass_points"] = random.choice(jsond3)
        p_id = place_map_id.index(place_target_type)
    #     # print(p_id,place_id[p_id],place_target_type)
    #     # peodic["pass_points"] .append(px)  # peole_path.get(people_id)
    #     # peodic["pass_points"] .append(px)
        RoadLine["firstPlaces"][p_id]["people"].append(peodic.copy())
    for h in range(500):
        if random.uniform(0, 1) > rate:
            continue
        place_target_type = PEOPLE.end1[h]
    #     (p_id8, p_point, jsond3) = paths[place_target_type]
    #     # paths.ge
    #     # print(len(jsond3[0]))
    #     # print(paths[people_type] )
        peodic["people_id"] = PEOPLE.id[h]
        peodic["people_type"] = PEOPLE.type[h]
        peodic["pass_points"] = PEOPLE.path2.pjson[h]
    #     # print(rd)
    #     peodic["pass_points"] = random.choice(jsond3)
        p_id = place_map_id.index(place_target_type)
    #     # print(p_id,place_id[p_id],place_target_type)
    #     # peodic["pass_points"] .append(px)  # peole_path.get(people_id)
    #     # peodic["pass_points"] .append(px)
        RoadLine["secondPlaces"][p_id]["people"].append(peodic.copy())
    #     asum.append(p_id)
    #     # print("place_id",RoadLine["places"][p_id]["place_id"],"place_type",place_target_type)
    # # print(asum)
    #
    spath = "D:/session/session_3/subject_2/ai_path_"+str(operate_id)+".json"

    with open(spath, 'w', encoding='utf-8') as f:
        f.write(json.dumps(RoadLine, ensure_ascii=False))
    spath = "D:/session/session_3/subject_2/team_path_"+str(operate_id)+".json"

    with open(spath, 'w', encoding='utf-8') as f:
        f.write(json.dumps(RoadLine, ensure_ascii=False))
    print("save path:", spath)


def s31_22json(data_set, operate_id, peoples):
    RoadLine = {
        "firstPlaces": [
            {
                "place_id": 1,
                "people": []
            },
            {
                "place_id": 2,
                "people": []
            },
            {
                "place_id": 3,
                "people": []
            }
        ],
        "secondPlaces": [
            {
                "place_id": 1,
                "people": []
            },
            {
                "place_id": 2,
                "people": []
            },
            {
                "place_id": 3,
                "people": []
            }
        ],
        "operate_id": operate_id
    }
    px = {"longitude": 105.53628319629698, "latitude": 38.832731900565818}
    # RoadLine["operate_id"] = 3
    peodic = {
        "people_id": 494,
        "people_type": 5,
        "pass_points":  []}
    # print(data_set, peole_path)
    # print((p1.new_pass_point_json))
    for h in range(500):
        peodic["pass_points"] = []
        people_id = int(data_set.iloc[h]["people_id"])
        people_type = int(data_set.iloc[h]["people_type"])
        place_id = int(data_set.iloc[h]["place_id"])
        peodic["people_id"] = people_id
        peodic["people_type"] = people_type
        peodic["pass_points"] = peoples[h].old_pass_point_json
        # peodic["pass_points"] .append(px)  # peole_path.get(people_id)

        RoadLine["firstPlaces"][place_id-1]["people"].append(peodic.copy())
    for h in range(500):
        peodic["pass_points"] = []
        people_id = int(data_set.iloc[h]["people_id"])
        people_type = int(data_set.iloc[h]["people_type"])
        place_id = int(data_set.iloc[h]["place_id"])
        peodic["people_id"] = people_id
        peodic["people_type"] = people_type
        peodic["pass_points"] = peoples[h].new_pass_point_json
        # peodic["pass_points"] .append(px)  # peole_path.get(people_id)

        RoadLine["secondPlaces"][place_id-1]["people"].append(peodic.copy())
    # print(RoadLine)

    # with open("D:/session/session_3/subject_2/team_path_"+str(operate_id)+".json", 'w', encoding='utf-8') as f:
    # path="C:\\Users\\Administrator\\Desktop\\Test_Exam\\session\\session_3\\subject_2\\team_path_"+str(operate_id)+".json"
    path = "D:/session/session_3/subject_2/team_path_"+str(operate_id)+".json"
    print(path)
    with open(path, 'w', encoding='utf-8') as f:
        f.write(json.dumps(RoadLine, ensure_ascii=False))
    path = "D:/session/session_3/subject_2/ai_path_"+str(operate_id)+".json"
    print(path)
    with open(path, 'w', encoding='utf-8') as f:
        f.write(json.dumps(RoadLine, ensure_ascii=False))


def getpoints_id_in_map(start_points, npallp):
    start_id = []
    # print(start_points, "")
    danp = np.array(start_points)
    for _val in danp[:, 0]:
        minay = abs(npallp[:, 0]-_val)
        start_id.append(np.argmin(minay))
    return start_id


def data2pandfram(data_set, place_id, _columns=['place_id']):
    data3 = pd.DataFrame(np.array(place_id), columns=_columns)
    data_set = pd.concat([data_set, data3], axis=1)
    return data_set


def s_id2points(path_id, points):
    px = {"longitude": 105.53628319629698, "latitude": 38.832731900565818}
    path_points = []
    path_point_json = []

    for val in path_id:
        path_points.append(points[val])
        px["latitude"] = points[val][1]
        px["longitude"] = points[val][0]
        path_point_json.append(px.copy())

    return path_points, path_point_json


def sim_sysytem(t_id, xyps, p1):
    p1.has_pass += p1.speed

    # print(t_id, p1.has_pass, p1.get_pass_id())


def preprocess(Objdll, s1, ipconfigPath):
    # 读图
    cf = configparser.ConfigParser()
    cf.read(ipconfigPath+"/ipconfig.ini")
    local_ip = cf.get("entrant", "ip")
    local_port = cf.get("entrant", "port")
    s1.bind((local_ip, int(local_port)))  # 绑定ip和端口
    # 设置发送（客户端）的ip和端口
    client_ip = cf.get("client", "ip")
    client_port = cf.get("client", "port")
    dest_dir = (client_ip, int(client_port))
    Globalvar.set_send_id_addr(dest_dir)
    # local_ip = udp.socket.gethostbyname(udp.socket.gethostname())
    # s1.bind((local_ip, 10014))
    # print("local_ip:",local_ip)
    print('Bind UDP on 10014...')
    # 创建线程接收数据
    recv_thread = udp.threading.Thread(target=udp.recvmsg, args=(s1, Objdll))
    recv_thread.start()
    return True


def session_3_2_main(Objdll, s):
    exam_round = 1
    # 判断每场考试是否结束，结束为true，否则为false，初始为true方便第一次发送
    finish = True
    while True:
        if finish:
            # 发送准备指令
            sesson1.send_ready(3, 2, exam_round, s)
            finish = False
        if Globalvar.get_recv_msg_content():
            Globalvar.set_recv_msg_content(False)
            # 根据报文读取对应科目、情景下的client_path_.json文件
            temp_content = Globalvar.get_msg_content_value()
            examRound = Globalvar.get_exam_round()
            view_ai_path(examRound)  # 算法主程序
            # client_path_content = read_client_path(temp_content[0], temp_content[1], exam_round=examRound)
            # if dlltest.transfer_client_path(Objdll, client_path_content, temp_content[0], temp_content[1]):
            # 数据传入完成，算法计算完毕，向平台发送完成指令
            udp.sentmsg(temp_content[0], temp_content[1], s, Globalvar.get_send_id_addr(
            ), exam_round=examRound, info=3)
            finish = True
            # 一场考试结束后将考试场次+1
            exam_round += 1
            print("运行成功，准备下次考试")


def recv_dynamic_information(flag, exam_round):
    if flag:
        global update_new_break
        update_new_break = True  # receive dynamic information
        global e_round
        e_round = exam_round

    # global e_round
    # e_round=operate_id


def GetDistance(p1, p2):
    lat1 = p1[1]
    long1 = p1[0]
    lat2 = p2[1]
    long2 = p2[0]
    if (lat1 == lat2) and long1 == long2:
        return 0
    val = np.sin(lat1 * 0.01745329) * np.sin(lat2 * 0.01745329) + np.cos(lat1 *
                                                                         0.01745329) * np.cos(lat2 * 0.01745329) * np.cos((long1 - long2) * 0.01745329)
    if(val > 1):
        # print(p1,p2)
        return 0
    return 6378137 * np.arccos(val)


def get_randm(paths):
    print("len:", len(paths))


def get_rate(operate_id):
    return 0.975



class _PATH():
    def __init__(self) -> None:
        self.map_id = list()
        self.point = list()
        self.pjson = list()
        self.cip = [list() for i in range(500)]  # 每一段的距离
        self.cid = [0 for i in range(500)]  # 每一段的距离
        self.has_pass = [0 for i in range(500)]

    def get_cip(self, index, point):
        for i in range(len(self.map_id[index])-1):
            id1 = self.map_id[index][i]
            id2 = self.map_id[index][i+1]
            val = GetDistance(point[id1], point[id2])
            self.cip[index].append(val)
        # print(self.cip[index])

    def get_pass_id(self, index):
        sum = 0
        for id, val in enumerate(self.cip[index]):
            sum += val
            if(sum > self.has_pass[index]):
                self.cid[index] = id
                # print(sum,self.has_pass[index],index,id)
                return id
        self.cid[index] = id
        return id

    def id2json(self, points):
        path_points = []
        px = {"longitude": 105.53628319629698, "latitude": 38.832731900565818}
        for line_id in self.map_id:  # 每条路
            # print(line)
            _points = list()
            jsond3 = list()
            for val in line_id:  # 每个点
                _points.append(points[val])
                px["latitude"] = points[val][1]
                px["longitude"] = points[val][0]
                jsond3.append(px.copy())
            path_points.append(_points.copy())
            self.pjson.append(jsond3.copy())


class _PEOPLE():
    def __init__(self) -> None:
        self.speed = list()

        self.id = list()
        self.type = list()
        self.start1 = list()
        self.start2 = list()
        self.end1 = list()
        self.end2 = list()
        self.path1 = _PATH()
        self.path2 = _PATH()
        self.end1_place_type = list()
        # print(self.cip)

    def outpath(self):
        return self.pass_point[:self.get_pass_id()]


def view_ai_path(operate_id=1001):
    client_path = "D:/session/session_3/subject_2/client_path_" + \
        str(operate_id)+".json"
    data_set, start_points, place_points, break_points, (
        place__index, place_type) = s31.read_client_data(client_path)
    points, roadLines, roadpoint = ng31. view_maps2(True)  # 读取地图
    out_edges, dictpoints = ng31.perdata(roadLines, points)  # 修正数据
    gant_src = nx.Graph()  # 创建：空的 无向图
    # 向图中添加多条赋权边: (node1,node2,weight)
    gant_src.add_weighted_edges_from(out_edges)

    npallp = np.array(points)
    start_id = getpoints_id_in_map(start_points, npallp)
    place_map_id = getpoints_id_in_map(place_points, npallp)
    break_id = getpoints_id_in_map(break_points, npallp)

    out_edges = []
    for x, y in roadpoint:
        # print(x,y)
        if(points[x] == points[y]):
            out_edges.append((x, y, 0.000))
            continue
        valdis = s31 .GetDistance(points[x], points[y])
        if(valdis < 7):
            out_edges.append((x, y, valdis))
            continue
    # 向图中添加多条赋权边: (node1,node2,weight)
    gant_src.add_weighted_edges_from(out_edges)

    roadpoint_np = np.array(roadpoint)
    for i, bi in enumerate(break_id):
        roadpoint_index = (roadpoint_np[:, 1] == bi)
        if len(roadpoint_np[roadpoint_index]) > 0:
            # print(roadpoint_np[roadpoint_index],roadpoint_np[roadpoint_index][0][1],i)
            break_id[i] = roadpoint_np[roadpoint_index][0][0]

    rd_edges = []  # 去掉断路的边，应该 try catch
    for i in range(int(len(break_id)*0.5)):
        rd_edges.append(nx.astar_path(
            gant_src, break_id[2*i], break_id[2*i+1]))
    gant_firstt_break = gant_src.copy()
    for eg in rd_edges:
        for val in range(len(eg)-1):
            # print(eg[val],eg[val+1])
            gant_firstt_break.remove_edge(eg[val], eg[val+1])

    paths = dict()
    paths_list = []
    for ii, eid in enumerate(place_map_id):
        path = []
        for sid in start_id:
            pt = nx.astar_path(gant_firstt_break, sid, eid)
            path.append(pt.copy())
            paths_list.append(pt.copy())
        paths[place_type[ii]] = path.copy()
    # peoples=[]
    PEOPLE = _PEOPLE()
    PEOPLE.type = data_set["people_type"].to_list()
    # print(PEOPLE.type )
    PEOPLE.speed = [speed_dict[val] for val in PEOPLE.type]
    #
    PEOPLE.id = data_set["people_id"].to_list()
    PEOPLE.start1 = [random.choice(start_id) for val in range(500)]
    # print(len(place_map_id))
    print(place_type, operate_id, place__index)
    PEOPLE.end1_place_type = gen_place(place_type, operate_id, place__index)
    for i in range(500):
        _index = place_type.index(PEOPLE.end1_place_type[i])
        PEOPLE.end1.append(place_map_id[_index])
    PEOPLE.end2 = PEOPLE.end1.copy()
    for i in range(500):
        sid = PEOPLE.start1[i]
        eid = PEOPLE.end1[i]
        PEOPLE.path1.map_id.append(nx.astar_path(gant_firstt_break, sid, eid))

    print("等待动态信息")
    cnt=0
    while not Globalvar.get_update_new_break_Flag():
        cnt+=1
        if(cnt>90):
            break
        time.sleep(1)  # wait for receive the new break information
    new_break_content, break_2_point = s31.read_new_break(
        3, operate_id, client_path)
    new_break_start_time = new_break_content["new_break_start_time"]
    print("new_break_start_time:", new_break_start_time)

    gant_secend_break = gant_firstt_break.copy()
    if not break_2_point == []:
        break_2_id = getpoints_id_in_map(break_2_point, npallp)
        break_paths = []  # 去掉断路的边，应该 try catch
        for i in range(int(len(break_2_id)*0.5)):
            break_paths.append(nx.astar_path(
                gant_src, break_2_id[2*i], break_2_id[2*i+1]))

        for break_path in break_paths:
            for _point_id in range(len(break_path)-1):
                # print(eg[val],eg[val+1])
                gant_secend_break.remove_edge(
                    break_path[_point_id], break_path[_point_id+1])

    PEOPLE.path1.has_pass = np.array(PEOPLE.speed)*new_break_start_time
    for i in range(500):
        PEOPLE.path1.get_cip(i, points)  # 计算每一段的距离
        PEOPLE.path1.get_pass_id(i)
        PEOPLE.start2.append(PEOPLE.path1.map_id[i][PEOPLE.path1.cid[i]])
        sid = PEOPLE.start2[i]
        eid = PEOPLE.end2[i]
        PEOPLE.path2.map_id.append(nx.astar_path(gant_secend_break, sid, eid))
    # print(PEOPLE.path1.cid)
    PEOPLE.path1.id2json(points)
    PEOPLE.path2.id2json(points)
    s31_2json_new(data_set, paths, place_points,
                  operate_id, place__index, place_type, PEOPLE, place_map_id)

    # print(PEOPLE.path1.pjson)
    # print(PEOPLE.path2.map_id[0])

    # for i in range(500):

    #     PEOPLE.path1.get_cip(i,points) #计算每一段的距离
    #     PEOPLE.path1.get_pass_id(i)
    # print(PEOPLE.path1.cid)
#     for h in range(500):
#         if random.uniform(0, 1) > rate:
#             continue
#         people_id = int(data_set.iloc[h]["people_id"])
#         people_type = int(data_set.iloc[h]["people_type"])
#         place_target_type = int(data_set.iloc[h]["place_id"])

#         (p_id8, p_point, jsond3) = paths[place_target_type]
#

    # for i in range(500):
    #     peoples.append(s31main.People())
    #     peoples[i].speed = speed_dict[people_type_list[i]]
# def view_ai_path2(operate_id=1001):
#     client_path = "D:/session/session_3/subject_2/client_path_" + \
#         str(operate_id)+".json"
#     data_set, start_points, place_points, break_points, (
#         place__index, place_type) = s31.read_client_data(client_path)
#     points, roadLines, roadpoint = ng31. view_maps2(True)  # 读取地图
#     out_edges, dictpoints = ng31.perdata(roadLines, points)  # 修正数据
#     gant_src = nx.Graph()  # 创建：空的 无向图
#     # 向图中添加多条赋权边: (node1,node2,weight)
#     gant_src.add_weighted_edges_from(out_edges)

#     npallp = np.array(points)
#     start_id = getpoints_id_in_map(start_points, npallp)
#     place_id = getpoints_id_in_map(place_points, npallp)
#     break_id = getpoints_id_in_map(break_points, npallp)

#     out_edges = []
#     for x, y in roadpoint:
#         # print(x,y)
#         if(points[x] == points[y]):
#             out_edges.append((x, y, 0.000))
#             continue
#         valdis = s31 .GetDistance(points[x], points[y])
#         if(valdis < 7):
#             out_edges.append((x, y, valdis))
#             continue
#     # 向图中添加多条赋权边: (node1,node2,weight)
#     gant_src.add_weighted_edges_from(out_edges)

#     roadpoint_np = np.array(roadpoint)
#     for i, bi in enumerate(break_id):
#         roadpoint_index = (roadpoint_np[:, 1] == bi)
#         if len(roadpoint_np[roadpoint_index]) > 0:
#             # print(roadpoint_np[roadpoint_index],roadpoint_np[roadpoint_index][0][1],i)
#             break_id[i] = roadpoint_np[roadpoint_index][0][0]

#     rd_edges = []  # 去掉断路的边，应该 try catch
#     for i in range(int(len(break_id)*0.5)):
#         rd_edges.append(nx.astar_path(
#             gant_src, break_id[2*i], break_id[2*i+1]))
#     gant_firstt_break = gant_src.copy()
#     for eg in rd_edges:
#         for val in range(len(eg)-1):
#             # print(eg[val],eg[val+1])
#             gant_firstt_break.remove_edge(eg[val], eg[val+1])

#     paths = dict()
#     paths_list = []
#     for ii, eid in enumerate(place_id):
#         path = []
#         for sid in start_id:
#             pt = nx.astar_path(gant_firstt_break, sid, eid)
#             path.append(pt.copy())
#             paths_list.append(pt.copy())
#         paths[place_type[ii]] = path.copy()
#     peoples=[]
#     for i in range(500):

#     data_set = s31main.data2pandfram(data_set, place_type,
#                              operate_id, place__index, _columns=["place_id"])
#     # print(data_set)
#     s31.id2points(paths, points)
#     # s31main.s31_2json(data_set, paths, place_points,
#             #   operate_id, place__index, place_type)

#     print("place_id ", place__index, "place_type ", place_type)
#     # px = {"longitude": 105.53628319629698, "latitude": 38.832731900565818}
#     # RoadLine["operate_id"] = 3
#     peodic = {
#         "people_id": 494,
#         "people_type": 5,
#         "pass_points":  []}
#     # print(data_set, len(peole_path))
#     # asum = []
#     rate = get_rate(operate_id)
#     print("rate ", rate)
#     peoples_paths=[]
#     peoples = []
#     people_type_list = data_set["people_type"].to_list()
#     for h in range(500):
#         if random.uniform(0, 1) > rate:
#             continue
#         people_id = int(data_set.iloc[h]["people_id"])
#         people_type = int(data_set.iloc[h]["people_type"])
#         place_target_type = int(data_set.iloc[h]["place_id"])

#         (p_id8, p_point, jsond3) = paths[place_target_type]
#         speed = speed_dict[people_type_list[i]]
#         peoples.append(
#             s31.People(pass_point=p_point, speed=speed, pass_id=p_id8))
#         peodic["pass_points"] = random.choice(jsond3)


#     path_points, path_point_json = s31.id2points_old(
#         paths_list, points, place_id)
#     place_id = []


#     print("Waiting for new break information.")
#     gant_secend_break = gant_firstt_break.copy()

#     new_break_content, break_2_point = s31.read_new_break(
#         3, operate_id, client_path)
#     if not break_2_point == []:
#         break_2_id = getpoints_id_in_map(break_2_point, npallp)
#     new_break_start_time = new_break_content["new_break_start_time"]
#     print("new_break_start_time:", new_break_start_time)

#     for h in range(500):
#         p1 = peoples[i]
#         p1.has_pass = p1.speed*new_break_start_time

#         # for t_id in range(new_break_start_time):
#         #     sim_sysytem(t_id, path_point, p1)
#         p1.new_start = p1.get_pass_id()  # 找到人的新起点序号
#     # print(paths[0])
#     # print(paths[0][0],paths[0][p1.new_start],paths[0][-1])
#     #
#         p1.new_pass_id = nx.astar_path(
#             gant_secend_break, paths_list[rd_index][p1.new_start-1], paths_list[rd_index][-1])
#     # print(paths[0][:p1.new_start])
#     # print(p1.new_pass_id )
#         # 点序号和坐标
#         p1.new_pass_point, p1.new_pass_point_json = s_id2points(
#             p1.new_pass_id, points)
#         p1.old_pass_point_json = path_point_json[rd_index][:p1.new_start]


#     # while not Globalvar.get_update_new_break_Flag():

#     #     time.sleep(1)  # wait for receive the new break information
#     # time.sleep(10)

#     # gant_src.add_weighted_edges_from(rd_edges)


#     # for i, bi in enumerate(break_2_id):
#     #     roadpoint_index = (roadpoint_np[:, 1] == bi)
#     #     if len(roadpoint_np[roadpoint_index]) > 0:
#     #         # print(roadpoint_np[roadpoint_index],roadpoint_np[roadpoint_index][0][1],i)
#     #         break_id[i] = roadpoint_np[roadpoint_index][0][0]

#         break_paths = []  # 去掉断路的边，应该 try catch
#         for i in range(int(len(break_2_id)*0.5)):
#             break_paths.append(nx.astar_path(
#                 gant_src, break_2_id[2*i], break_2_id[2*i+1]))

#         for break_path in break_paths:
#             for _point_id in range(len(break_path)-1):
#                 # print(eg[val],eg[val+1])
#                 gant_secend_break.remove_edge(
#                     break_path[_point_id], break_path[_point_id+1])


#     for i in range(500):
#         place_id.append(random.randint(1, 3))  # 随机选终点
#         rd_index = random.randint(0, 11)  # 随机选路径
#         speed = speed_dict[people_type_list[i]]
#         # print(speed)
#         # 创建一个智能体
#         # print(path_points[rd_index])
#         # print(paths_list[rd_index])
#         peoples.append(
#             s31.People(pass_point=path_points[rd_index], speed=speed, pass_id=paths_list[rd_index]))
#         p1 = peoples[i]
#         p1.has_pass = p1.speed*new_break_start_time

#         # for t_id in range(new_break_start_time):
#         #     sim_sysytem(t_id, path_point, p1)
#         p1.new_start = p1.get_pass_id()  # 找到人的新起点序号
#     # print(paths[0])
#     # print(paths[0][0],paths[0][p1.new_start],paths[0][-1])
#     #
#         p1.new_pass_id = nx.astar_path(
#             gant_secend_break, paths_list[rd_index][p1.new_start-1], paths_list[rd_index][-1])
#     # print(paths[0][:p1.new_start])
#     # print(p1.new_pass_id )
#         # 点序号和坐标
#         p1.new_pass_point, p1.new_pass_point_json = s_id2points(
#             p1.new_pass_id, points)
#         p1.old_pass_point_json = path_point_json[rd_index][:p1.new_start]
#     # print(p1.new_pass_point)
#     # print(p1.new_pass_point_json)
#     data_set = data2pandfram(data_set, place_id, _columns=["place_id"])


if __name__ == '__main__':
    pass
    # view_ai_path(1)
